
let BaseService = require('./base');
class ResourceService extends BaseService {
    constructor(...args){
      super(...args);
      this.model = 'role';
    }
    async select(pageNum=1,pageSize=3,where={}){
      let {app} = this;
      let list =  await app.mysql.select(this.model,{
        where,
        orders:[['id','asc']],//指定排序字段和排序的顺序
        offset:(pageNum-1)*pageSize,
        limit:pageSize
      });
      //给每个角色增加一个属性 resourceIds
      for(let i=0;i<list.length;i++){
        let roleId = list[i].id;
        let rows = await app.mysql.select('role_resource',{where:{role_id:roleId}});
        list[i].resourceIds = rows.map(row=>row['resource_id']);
        rows = await app.mysql.select('role_user',{where:{role_id:roleId}});
        list[i].userIds = rows.map(row=>row['user_id']);
      }
      console.log(list);
      let total = await app.mysql.count(this.model,where);
      return {list,total};
   }

    async getResources(){
      let {app} = this;
      let resources = await app.mysql.select('resource',{orders:[['id','asc']]});
      let rootResources = [];//顶级权限
      resources.forEach(resource=>{
        if(resource.parent_id == 0){//如果父ID是0的话表示顶级菜单
          rootResources.push(resource);
        }else{//说明不是顶级菜单
          let parent = resources.find(item=>item.id == resource.parent_id); 
          if(parent){
            parent.children||(parent.children = []);
            parent.children.push(resource);
          }
        }
      }); 
      //先把所有元素都放在Map里
     /*  let Map = {};
      resources.forEach(resource=>{
        Map[resource.id] = resource;
      }); */

      
      return rootResources;
    }

    async setResources(roleId,resourceIds){
      let {app} = this;
      //因为这些SQL语句是一个整体，要么都成功，要么都失败,所以要封装成一个事务
      let conn = await app.mysql.beginTransaction();
      try{
        await conn.delete('role_resource',{'role_id':roleId});
        for(let i=0;i<resourceIds.length;i++){
          await conn.insert('role_resource',{role_id:roleId,resource_id:resourceIds[i]});
        }
        await conn.commit();
        return 1;
      }catch(error){
        await conn.rollback();
        return 0;
      }
    }

    async getUsers(){
      let {app} = this;
      let users = await app.mysql.select('user',{orders:[['id','asc']]});
      return users;
    }

    async setUsers(roleId,users){
      let {app} = this;
      //因为这些SQL语句是一个整体，要么都成功，要么都失败,所以要封装成一个事务
      let conn = await app.mysql.beginTransaction();
      try{
        await conn.delete('role_user',{'role_id':roleId});
        for(let i=0;i<users.length;i++){
          await conn.insert('role_user',{role_id:roleId,user_id:users[i]});
        }
        await conn.commit();
        return 1;
      }catch(error){
        await conn.rollback();
        return 0;
      }
    }
}
module.exports = ResourceService;